<script setup lang="ts">
import { ElTree } from 'element-plus'
import type { TreeOptionProps } from 'element-plus/es/components/tree/src/tree.type'
import {
  type Point,
  usePointTree,
  useTreeFilter,
} from './ReadonlyPointTree'

defineOptions({
  inheritAttrs: false,
})

const props = withDefaults(
  defineProps<{
    showTitle?: boolean
    title?: string
    external?: boolean
    points?: Point[]
    treeProps?: TreeOptionProps
    showFilter?: boolean
    needFullName?: 0 | 1
    /** 是否默认选中第一棵树的根节点 */
    fire?: boolean
  }>(),
  {
    showTitle: true,
    title: '用能单元（点位）',
    points: () => [],
    treeProps: () => ({
      label: 'pointName',
    }),
    showFilter: true,
    external: false,
    needFullName: 0,
  },
)

const emits = defineEmits<{
  (e: 'click-node', o: Point): void
}>()

const { treeData, defaultTreeExpandKeys, vLoading, getTreeData } = usePointTree()
const [current, setCurrent] = useState<Point | null>(null)
const data = computed(() => {
  return props.external ? props.points : treeData.value
})

const treeRef = ref<InstanceType<typeof ElTree>>()

const { filterTextInput, filterNode } = useTreeFilter(
  'pointName',
  (val: string) => treeRef.value?.filter?.(val),
)
watch(
  () => props.external,
  (b: boolean) => {
    if (b)
      return
    getTreeData(props.needFullName, (o: Point[]) => {
      if (props.fire && o[0]) {
        treeRef.value?.setCurrentKey?.(o[0]?.id)
        clickNode({
          ...o[0],
          children: [],
        })
      }
    })
  },
  {
    immediate: true,
  },
)

function clickNode(o: Point) {
  setCurrent(o)
  emits('click-node', o)
}

defineExpose({
  current,
  treeData,
  getTreeData,
  setCurrentKey: (key: string) => {
    treeRef.value?.setCurrentKey?.(key)
  },
})
</script>

<template>
  <div
    v-loading
    class="height-fill flex-incompressible view-tree box-border"
  >
    <h5
      v-if="showTitle"
      class="flex-incompressible align-center margin-0 flex justify-between"
    >
      <slot name="title">
        <span>{{ title }}</span>
      </slot>
    </h5>
    <ElInput
      v-if="showFilter"
      v-model="filterTextInput"
      placeholder="关键字"
      class="flex-incompressible free"
      clearable
    />
    <ElScrollbar>
      <ElTree
        ref="treeRef"
        class="flex-fillRemaining"
        :data="data"
        :props="treeProps"
        highlight-current
        :default-expanded-keys="defaultTreeExpandKeys"
        node-key="id"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        v-bind="$attrs"
        @contextmenu.prevent
        @node-click="clickNode"
      >
        <template #default="{ node }">
          <div
            class="flex-fillRemaining align-center custom-tree-node flex"
          >
            <span>{{ node.label }}</span>
          </div>
        </template>
      </ElTree>
    </ElScrollbar>
  </div>
</template>
